<?php

namespace app\store\model;

use app\common\model\OrderRefund as OrderRefundModel;

use app\store\model\User as UserModel;
use app\common\service\Message as MessageService;
use app\common\service\order\Refund as RefundService;
use app\common\enum\OrderType as OrderTypeEnum;

/**
 * 售后单模型
 * Class OrderRefund
 * @package app\api\model
 */
class OrderRefund extends OrderRefundModel
{
    /**
     * 获取售后单列表
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($query = [])
    {
        // 查询条件：订单号
        if (isset($query['order_no']) && !empty($query['order_no'])) {
            $this->where('order.order_no', 'like', "%{$query['order_no']}%");
        }
        // 查询条件：起始日期
        if (isset($query['start_time']) && !empty($query['start_time'])) {
            $this->where('m.create_time', '>=', strtotime($query['start_time']));
        }
        // 查询条件：截止日期
        if (isset($query['end_time']) && !empty($query['end_time'])) {
            $this->where('m.create_time', '<', strtotime($query['end_time']) + 86400);
        }
        // 售后类型
        if (isset($query['type']) && $query['type'] > 0) {
            $this->where('m.type', '=', $query['type']);
        }
        // 处理状态
        if (isset($query['state']) && is_numeric($query['state'])) {
            $this->where('m.status', '=', $query['state']);
        }
        // 获取列表数据
        return $this->alias('m')
            ->field('m.*, order.order_no')
            ->with(['order_goods.image', 'orderMaster', 'user'])
            ->join('order', 'order.order_id = m.order_id')
            ->order(['m.create_time' => 'desc'])
            ->paginate(10, false, [
                'query' => \request()->request()
            ]);
    }

    /**
     * 商家审核
     * @param $data
     * @return bool
     */
    public function audit($data)
    {
        if ($data['is_agree'] == 20 && empty($data['refuse_desc'])) {
            $this->error = '请输入拒绝原因';
            return false;
        }
        if ($data['is_agree'] == 10 && empty($data['address_id'])) {
            $this->error = '请选择退货地址';
            return false;
        }
        $this->transaction(function () use ($data) {
            // 拒绝申请, 标记售后单状态为已拒绝
            $data['is_agree'] == 20 && $data['status'] = 10;
            // 同意换货申请, 标记售后单状态为已完成
            $data['is_agree'] == 10 && $this['type']['value'] == 20 && $data['status'] = 20;
            // 更新退款单状态
            $this->allowField(true)->save($data);
            // 同意售后申请, 记录退货地址
            if ($data['is_agree'] == 10) {
                (new OrderRefundAddress)->add($this['order_refund_id'], $data['address_id']);
            }
            // 订单详情
            $order = Order::detail($this['order_id']);
            // 发送消息通知
            MessageService::send('order.refund', [
                'refund' => $this,    // 退款单信息
                'order_no' => $order['order_no'],      // 订单信息
                'order_type' => OrderTypeEnum::MASTER,   // 订单类型
            ]);
        });
        return true;
    }

    /**
     * 确认收货并退款
     * @param $data
     * @return bool
     * @throws \think\exception\DbException
     */
    public function receipt($data)
    {
        // 订单详情
        $order = Order::detail($this['order_id']);
        if ($data['refund_money'] > min($order['pay_price'], $this['order_goods']['total_pay_price'])) {
            $this->error = '退款金额不能大于商品实付款金额';
            return false;
        }
        $this->transaction(function () use ($order, $data) {
            // 更新售后单状态
            $this->allowField(true)->save([
                'refund_money' => $data['refund_money'],
                'is_receipt' => 1,
                'payment_type' => 3,
                'status' => 20
            ]);
            // 执行原路退款
            (new RefundService)->execute($order, $data['refund_money']);
            // 发送消息通知
            MessageService::send('order.refund', [
                'refund' => $this,    // 退款单信息
                'order_no' => $order['order_no'],      // 订单信息
                'order_type' => OrderTypeEnum::MASTER,   // 订单类型
            ]);
            // 消减用户的实际消费金额
            // 撤回自己的消费金额
            (new UserModel)->setDecUserExpend($this['user_id'], $this['pay_price']);
            if($this['user_id']){
                $user_1 = model('user')->where('user_id',$this['user_id'])->find();
                $user_upgrade_1 = model('user_grade')->where('grade_id',$user_1['grade_id'])->value('upgrade');
                if($user_1['grade_id'] == 1){
                    $upgrade_num = $user_1['first_num'];
                    $text1 = '';
                    $text = 'first_num';
                }elseif($user_1['grade_id'] == 2){
                    $upgrade_num = $user_1['second_num'];
                    $text1 = 'first_num';
                    $text = 'second_num';
                }elseif($user_1['grade_id'] == 3){
                    $upgrade_num = $user_1['third_num'];
                    $text1 = 'second_num';
                    $text = 'third_num';
                }elseif($user_1['grade_id'] == 4){
                    $upgrade_num = $user_1['four_num'];
                    $text1 = 'third_num';
                    $text = 'four_num';
                }elseif($user_1['grade_id'] == 5){
                    $upgrade_num = $user_1['five_num'];
                    $text1 = 'four_num';
                    $text = 'five_num';
                }elseif($user_1['grade_id'] == 6){
                    $upgrade_num = $user_1['six_num'];
                    $text1 = 'five_num';
                    $text = 'six_num';
                }elseif($user_1['grade_id'] == 7){
                    $upgrade_num = $user_1['seven_num'];
                    $text1 = 'six_num';
                    $text = 'seven_num';
                }
                $upgrade_1 = json_decode($user_upgrade_1,true);
                $user_grade_1 = model('user_grade')->where(['status'=>1])->order('grade_id desc')->select();
                $grade_id = 0;
                foreach ($user_grade_1 as $values){
                    $upgrade_2 = json_decode($values['upgrade'],true);
                    if($upgrade_2['expend_money'] > $user_1['expend_money']){
                        $grade_id = $values['grade_id'] - 1 ;
                    }

                }
                if($upgrade_1['upgrade_num'] > 0){
                    if($upgrade_1['expend_money'] > $user_1['expend_money'] && $upgrade_1['upgrade_num'] >= $upgrade_num){
                        $res = model('user')->where('user_id',$user_1['user_id'])->setField('grade_id',$grade_id);
                        //降级后把上级团队人数减一
                        if($res && !$text && $user_1['referee_id'] != 0){
                            $s_num = model('user')->where('user_id',$user_1['referee_id'])->value($text);
                            if($s_num > 0){
                                model('user')->where('user_id',$user_1['referee_id'])->setDec($text,1);
                            }
                        }
                        //团队下一等级加一
                        if ($text1 != '') {
                            $ss_num = model('user')->where('user_id',$user_1['referee_id'])->value($text1);
                            if($ss_num > 0) {
                                model('user')->where('user_id', $user_1['referee_id'])->setInc($text1, 1);
                            }
                        }
                    }
                }else{
                    if($upgrade_1['expend_money'] > $user_1['expend_money'] ){
                        $res = model('user')->where('user_id',$user_1['user_id'])->setField('grade_id',$grade_id);
                        //降级后把上级团队人数减一
                        if($res && !$text && $user_1['referee_id'] != 0){
                            $s_num = model('user')->where('user_id',$user_1['referee_id'])->value($text);
                            if($s_num > 0){
                                model('user')->where('user_id',$user_1['referee_id'])->setDec($text,1);
                            }
                        }
                        //团队下一等级加一
                        if ($text1 != '') {
                            $ss_num = model('user')->where('user_id',$user_1['referee_id'])->value($text1);
                            if($ss_num > 0) {
                                model('user')->where('user_id', $user_1['referee_id'])->setInc($text1, 1);
                            }
                        }
                    }
                }

            }
            // 条件：判断订单是否已结算
//            if ($order['is_settled'] == true) {
//                (new UserModel)->setDecUserExpend($order['user_id'], $data['refund_money']);
//            }else{
            //撤回佣金
            $user_capital = db('user_capital')->where(['order_no'=>$order['order_no']])->select();
            foreach ($user_capital as $v){
                if($v['type'] == 2){
                    model('user')->where('user_id',$v['user_id'])->setDec('balance',$v['money']);
                }
                model('user_capital')->where('id',$v['id'])->setField('type',3);
            }
            //去除团队消费金额
            $user_expend = db('user_expend')->where(['order_no'=>$order['order_no']])->select();
            if(!empty($user_expend)){
                foreach ($user_expend as $value){
                    (new UserModel)->setDecUserExpend($value['user_id'], $value['money']);
                    model('user_expend')->where(['order_no'=>$order['order_no'],'user_id'=>$value['user_id'],'type'=>1])->setField('type',2);
                    $user = model('user')->where('user_id',$value['user_id'])->find();
                    $user_upgrade = model('user_grade')->where('grade_id',$user['grade_id'])->value('upgrade');
                    //upgrade expend_money
                    $text1 = '';
                    $text = '';
                    if($user['grade_id'] == 1){
                        $upgrade_num = $user['first_num'];
                        $text1 = '';
                        $text = 'first_num';
                    }elseif($user['grade_id'] == 2){
                        $upgrade_num = $user['second_num'];
                        $text1 = 'first_num';
                        $text = 'second_num';
                    }elseif($user['grade_id'] == 3){
                        $upgrade_num = $user['third_num'];
                        $text1 = 'second_num';
                        $text = 'third_num';
                    }elseif($user['grade_id'] == 4){
                        $upgrade_num = $user['four_num'];
                        $text1 = 'third_num';
                        $text = 'four_num';
                    }elseif($user['grade_id'] == 5){
                        $upgrade_num = $user['five_num'];
                        $text1 = 'four_num';
                        $text = 'five_num';
                    }elseif($user['grade_id'] == 6){
                        $upgrade_num = $user['six_num'];
                        $text1 = 'five_num';
                        $text = 'six_num';
                    }elseif($user['grade_id'] == 7){
                        $upgrade_num = $user['seven_num'];
                        $text1 = 'six_num';
                        $text = 'seven_num';
                    }
                    $upgrade = json_decode($user_upgrade,true);
                    $user_grade_2 = model('user_grade')->where(['status'=>1])->order('grade_id desc')->select();
                    $grade_id = 0;
                    foreach ($user_grade_2 as $valuess){
                        $upgrade_2_1 = json_decode($valuess['upgrade'],true);
                        if($upgrade_2_1['expend_money'] > $user['expend_money']){
                            $grade_id = $valuess['grade_id'] - 1 ;
                        }

                    }
                    if($upgrade['upgrade_num'] > 0) {
                        if($upgrade['expend_money'] > $user['expend_money'] && $upgrade['upgrade_num'] >= $upgrade_num) {
                            $res = model('user')->where('user_id', $user['user_id'])->setField('grade_id', $grade_id);
                            //降级后把上级团队人数减一
                            if ($res && !$text && $user['referee_id'] != 0) {
                                $s_num = model('user')->where('user_id', $user['referee_id'])->value($text);
                                if ($s_num > 0) {
                                    model('user')->where('user_id', $user['referee_id'])->setDec($text, 1);
                                }
                            }
                            //团队下一等级加一
                            if ($text1 != '') {
                                $ss_num = model('user')->where('user_id',$user_1['referee_id'])->value($text1);
                                if($ss_num > 0) {
                                    model('user')->where('user_id', $user_1['referee_id'])->setInc($text1, 1);
                                }
                            }
                        }
                    }else{
                        if($upgrade['expend_money'] > $user['expend_money'] ) {
                            $res = model('user')->where('user_id', $user['user_id'])->setField('grade_id', $grade_id);
                            //降级后把上级团队人数减一
                            if ($res && !$text && $user['referee_id'] != 0) {
                                $s_num = model('user')->where('user_id', $user['referee_id'])->value($text);
                                if ($s_num > 0) {
                                    model('user')->where('user_id', $user['referee_id'])->setDec($text, 1);
                                }
                            }
                            //团队下一等级加一
                            if ($text1 != '') {
                                $ss_num = model('user')->where('user_id',$user_1['referee_id'])->value($text1);
                                if($ss_num > 0) {
                                    model('user')->where('user_id', $user_1['referee_id'])->setInc($text1, 1);
                                }
                            }
                        }

                    }
                }
            }
//            }

        });
        return true;
    }

}